package com.panda.pandawash.fragment;


import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.exception.DbException;
import com.panda.pandawash.R;
import com.panda.pandawash.activity.MotorMonitorActivity;
import com.panda.pandawash.application.CDApplication;
import com.panda.pandawash.bean.BindDevicesBean;
import com.panda.pandawash.model.MotorDeviceInfoMessage;
import com.panda.pandawash.model.MotorSingleStatusMessage;
import com.panda.pandawash.util.ProductsListUtils;
import com.panda.pandawash.util.SelfDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by gaowf on 2017/2/22.
 */

public class MonitorStatusFragment extends Fragment  {

    private String TAG = "MonitorStatusFragment";
    private Button mStartUpButton;
    private Button mShutdownButton;
    private TextView mTotalTimeTextView;
    private TextView mTotalWaterTextView;
    private TextView mTotalPowerTextView;

    private TextView mDeviceStatus;
    private ImageView mDeviceSwitch;

    private TextView mMotorUserVoltageTextView;
    private TextView mMotorUserCurrentTextView;

    private TextView mWaterPricePerStereTextView;
    private TextView mPowerPricePerDuTextView;

    private TextView mShutDownTextView;

    private TextView mTotalDuTextView;
    private TextView mTotalStereTextView;

    private TextView mTotalMoneyforPowerTextView;
    private TextView mTotalMoneyforWaterTextView;

    private Context mContext;
    private ImageView mrunning_status;//zhuji
    private ImageView mShutdown_status; //shuiqiang
    private ImageView mMotorRuning_status;//dianji

    private Boolean isruning = false;
    private Handler mRuningHandler;

    public final static int CONNECTED_FLAG = 0x10;
    public final static int UPDATE_USER_INFO = 0x20;
    public final static int UPDATE_DEV_INFO = 0x21;
    public final static String MOTOR_RUNING = "runing";
    public final static String MOTOR_RUNING_TIME = "runingtime";
    public final static String MOTOR_WATER = "water";
    public final static String MOTOR_POWER = "power";
    public final static String MOTOR_DEV_INFO = "devinfo";

    boolean motor_is_working = false;
    boolean motor_signal_led = false;
    boolean motor_running_led = false;
    private float water_price = (float) 3.40;
    private float power_price = (float) 0.57;

    private Button btn1, btn2;
    private SelfDialog mSelfDialog;	//自定义一个对话框

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View fragmentView = inflater.inflate(R.layout.monitor_status_layout, container, false);
        MotorMonitorActivity monitorActivity = (MotorMonitorActivity) getActivity();
        Log.d(TAG, "MonitorStatusFragment");
        mStartUpButton = (Button) fragmentView.findViewById(R.id.startupmotor);
        mShutdownButton = (Button) fragmentView.findViewById(R.id.shutdownmotor);

        mTotalTimeTextView = (TextView) fragmentView.findViewById(R.id.runingtime);

        mTotalMoneyforPowerTextView = (TextView) fragmentView.findViewById(R.id.usedpower_price);
        mTotalMoneyforWaterTextView = (TextView) fragmentView.findViewById(R.id.usedwater_price);
        mShutDownTextView = (TextView)fragmentView.findViewById(R.id.shutgun_times);

        mPowerPricePerDuTextView = (TextView) fragmentView.findViewById(R.id.priceperw_textview);
        mWaterPricePerStereTextView = (TextView) fragmentView.findViewById(R.id.priceperm_textview);

        mTotalDuTextView = (TextView) fragmentView.findViewById(R.id.motor_used_power);
        mTotalStereTextView = (TextView) fragmentView.findViewById(R.id.motor_used_water);

        mDeviceStatus = (TextView) fragmentView.findViewById(R.id.device_switch_status);
        mDeviceSwitch = (ImageView) fragmentView.findViewById(R.id.device_switch_btn);
        mDeviceSwitch.setOnClickListener(mOnClickListener);
        mrunning_status = (ImageView) fragmentView.findViewById(R.id.running_status);

        mMotorRuning_status = (ImageView) fragmentView.findViewById(R.id.motor_is_running);

        mMotorUserVoltageTextView = (TextView) fragmentView.findViewById(R.id.motor_user_voltage);
        mMotorUserCurrentTextView = (TextView) fragmentView.findViewById(R.id.motor_user_current);
        mShutdown_status = (ImageView) fragmentView.findViewById(R.id.motor_shutdown_status);

        mStartUpButton.setOnClickListener(mOnClickListener);
        mShutdownButton.setOnClickListener(mOnClickListener);
        mStartUpButton.setClickable(false);
        mShutdownButton.setClickable(false);
        // mRuningHandler = new Handler();


        btn1 = (Button) fragmentView.findViewById(R.id.btn1);
        btn2 = (Button) fragmentView.findViewById(R.id.btn2);
        btn1.setOnClickListener(mOnClickListener);
        btn2.setOnClickListener(mOnClickListener);

        mPowerPricePerDuTextView.setOnClickListener(mOnClickListener);
        mWaterPricePerStereTextView.setOnClickListener(mOnClickListener);
        SharedPreferences mSharedPreferences = getActivity().getSharedPreferences("init", Activity.MODE_PRIVATE);
        water_price = mSharedPreferences.getFloat("water_price", (float) 3.40);
        power_price = mSharedPreferences.getFloat("power_price", (float) 0.57);

        mPowerPricePerDuTextView.setText(String.format("%.3f ", power_price));
        mWaterPricePerStereTextView.setText(String.format("%.3f ", water_price));

        return fragmentView;
    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
    }

    @Override
    public void onDestroyView() {
        // TODO Auto-generated method stub
        super.onDestroyView();
        mHandler.removeCallbacksAndMessages(null);
    }

    private OnClickListener mOnClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
                case R.id.startupmotor:
                    Log.d(TAG, "startupmotor");
                    MotorStartUp();

                    break;

                case R.id.shutdownmotor:
                    Log.d(TAG, "shutdownmotor");
                    MotorShutDown();
                    break;

                case R.id.priceperm_textview:
                    Log.i(TAG, "priceperm_textview");
                    //showwaterproceDialog();
                    showDialog(1, null, InputType.TYPE_CLASS_NUMBER |InputType.TYPE_NUMBER_FLAG_DECIMAL, "请输入水价", "", mWaterPricePerStereTextView, mTotalMoneyforWaterTextView);
                    break;

                case R.id.priceperw_textview:
                    Log.i(TAG, "priceperw_textview");
                    //showpowerproceDialog();
                    showDialog(0, null, InputType.TYPE_CLASS_NUMBER |InputType.TYPE_NUMBER_FLAG_DECIMAL, "请输入电价", "", mPowerPricePerDuTextView, mTotalMoneyforPowerTextView);
                    break;

                case R.id.btn1:
                    findDevice(1);
                    break;

                case R.id.btn2:
                    updateBindDevices(100, "BEAR", "08:7C:BE:86:53:36");
                    break;

                case R.id.device_switch_btn:
                    if(motor_is_working){
                        MotorShutDown();
                        motor_is_working = false;
                    }else{
                        MotorStartUp();
                        motor_is_working = true;

                    }

                    break;


                default:
                    break;
            }
        }
    };


    private void updateBindDevices(int model, String name, String mac_address) {
        DbUtils dbUtils = CDApplication.getIntance().getDbUtil();
        BindDevicesBean bindDevicesBean = new BindDevicesBean();
        bindDevicesBean.setModel(model);
        bindDevicesBean.setName(name);
        bindDevicesBean.setMacAddress(mac_address);

        try {
            dbUtils.update(bindDevicesBean, WhereBuilder.b("mac_address", "=", mac_address), "name", "model");
        } catch (DbException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    private void findDevice(int id) {
        DbUtils dbUtils = CDApplication.getIntance().getDbUtil();

        try {
            BindDevicesBean deviceSelest = dbUtils.findFirst(Selector.from(BindDevicesBean.class).where("id", "=", id));
            Log.i("bear_", "id = " + deviceSelest.getId() + "\nname = " + deviceSelest.getName() + "\nmodel = " + deviceSelest.getModel());

        } catch (DbException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }
    }

    public void MotorStartUp() {
        MotorMonitorActivity mMotorMonitorActivity = (MotorMonitorActivity) getActivity();
        if (mMotorMonitorActivity != null)
        mMotorMonitorActivity.RobotStartUp();

    }

    public void MotorShutDown() {
        MotorMonitorActivity mMotorMonitorActivity = (MotorMonitorActivity) getActivity();
        if (mMotorMonitorActivity != null)
        mMotorMonitorActivity.RobotShutdown();
    }

    public void MotorGetInfo() {
        MotorMonitorActivity mMotorMonitorActivity = (MotorMonitorActivity) getActivity();
        if (mMotorMonitorActivity != null)
        mMotorMonitorActivity.RobotInfo();
    }

    public void MotorGetStatus() {
        MotorMonitorActivity mMotorMonitorActivity = (MotorMonitorActivity) getActivity();
        if (mMotorMonitorActivity != null)
        mMotorMonitorActivity.RobotStatus();
    }

    private void setTotalPower() {

        float price = Float.parseFloat(mPowerPricePerDuTextView.getText().toString());
        float total = Float.parseFloat(mTotalDuTextView.getText().toString());
        float value = price * total;
        mTotalMoneyforPowerTextView.setText(String.format("%.3f ", value));

    }

    private void setTotalWater() {

        float price = Float.parseFloat(mWaterPricePerStereTextView.getText().toString().trim());
        float total = Float.parseFloat(mTotalStereTextView.getText().toString().trim());
        float value = price * total;

        mTotalMoneyforWaterTextView.setText(String.format("%.3f ", value));
    }

    public void setTotalTime(String string) {
        Log.d(TAG, "Total Time:" + string);
        mTotalTimeTextView.setText(string);

    }

    private Handler mHandler = new Handler() {

        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case CONNECTED_FLAG:
                    if (msg.getData().getBoolean(MOTOR_RUNING)) {
                        Log.i(TAG, "开机成功");
                        isruning = true;
                        mStartUpButton.setClickable(true);
                        mShutdownButton.setClickable(true);
                        mrunning_status.setImageDrawable(getResources().getDrawable(R.drawable.ic_zhuji_on));
                        mMotorRuning_status.setImageDrawable(getResources().getDrawable(R.drawable.ic_dianji_on));
                        mDeviceStatus.setText(getResources().getString(R.string.poweron_str));
                        mDeviceSwitch.setImageDrawable(getResources().getDrawable(R.drawable.device_info_on));

                        //mrunning_status.setImageDrawable(getResources().getDrawable(R.drawable.green));
                    } else {
                        Log.i(TAG, "关机成功");
                        mStartUpButton.setClickable(true);
                        mShutdownButton.setClickable(true);
                        mrunning_status.setImageDrawable(getResources().getDrawable(R.drawable.ic_zhuji_off));
                        mMotorRuning_status.setImageDrawable(getResources().getDrawable(R.drawable.ic_dianji_off));
                        mDeviceStatus.setText(getResources().getString(R.string.poweroff_str));
                        mDeviceSwitch.setImageDrawable(getResources().getDrawable(R.drawable.device_info_off));
                        //	mrunning_status.setImageDrawable(getResources().getDrawable(R.drawable.red));

                    }

                    break;
                case UPDATE_DEV_INFO: {

                    Log.i(TAG, " UPDATE_DEV_INFO info");

                    String info = msg.getData().getString(MOTOR_DEV_INFO);

                    try {
                        JSONObject object = new JSONObject(info);

                        String motor_runed_time = object.getString(MotorDeviceInfoMessage.MOTOR_RUNED_TIME);
                        String motor_current_voltage = object.getString(MotorSingleStatusMessage.MOTOR_SINGLE_STATUS_VOLTAGE);
                        String motor_current_current = object.getString(MotorSingleStatusMessage.MOTOR_SINGLE_STATUS_CURRENT);

                        motor_is_working = object.getBoolean(MotorSingleStatusMessage.MOTOR_IS_WORKING);
                        motor_signal_led = object.getBoolean(MotorSingleStatusMessage.MOTOR_SIGNAL_LED_STATUS_CURRENT);
                        motor_running_led = object.getBoolean(MotorSingleStatusMessage.MOTOR_RUNING_LED_STATUS_CURRENT);
                        String energyString = object.getString(MotorDeviceInfoMessage.MOTOR_USED_ENERGY);


                        double watergun_time = object.getDouble(MotorDeviceInfoMessage.MOTOR_USED_WATER_TIME);
                        String shutgun_timeString = object.getString(MotorDeviceInfoMessage.MOTOR_START_TIMES);
                        MotorMonitorActivity monitorActivity = (MotorMonitorActivity)getActivity();
                        if (monitorActivity == null)
                            return;
                        int model = monitorActivity.getmDeviceModel();
                        List<Map<String, Object>> infoMaps = ProductsListUtils.getProductsList();

                        HashMap<String, Object> hashMap = (HashMap<String, Object>) infoMaps.get(model);
                        Double data = (Double) hashMap.get("device_flow");

                        float water_cap = (float) (watergun_time * data);

                        if (motor_is_working) {
                            Log.i("Led", "主机开");
                            mrunning_status.setImageDrawable(getResources().getDrawable(R.drawable.ic_zhuji_on));
                            mDeviceStatus.setText(getResources().getString(R.string.poweron_str));
                            mDeviceSwitch.setImageDrawable(getResources().getDrawable(R.drawable.device_info_on));
                            if (motor_running_led) {
                                Log.i("Led", "电机开");
                                mMotorRuning_status.setImageDrawable(getResources().getDrawable(R.drawable.ic_dianji_on));
                            } else {
                                Log.i("Led", "电机关");
                                mMotorRuning_status.setImageDrawable(getResources().getDrawable(R.drawable.ic_dianji_off));
                            }

                        } else {
                            Log.i("Led", "主机关");
                            mrunning_status.setImageDrawable(getResources().getDrawable(R.drawable.ic_zhuji_off));
                            mMotorRuning_status.setImageDrawable(getResources().getDrawable(R.drawable.ic_dianji_off));
                            mDeviceStatus.setText(getResources().getString(R.string.poweroff_str));
                            mDeviceSwitch.setImageDrawable(getResources().getDrawable(R.drawable.device_info_off));
                        }

                        if (motor_signal_led) {
                            Log.i("Led", "水枪开");
                            mShutdown_status.setImageDrawable(getResources().getDrawable(R.drawable.ic_shuiqiang_on));
                        } else {
                            Log.i("Led", "水枪关");
                            mShutdown_status.setImageDrawable(getResources().getDrawable(R.drawable.ic_shuiqiang_off));
                        }


                        mMotorUserVoltageTextView.setText(motor_current_voltage);
                        mMotorUserCurrentTextView.setText(motor_current_current);
                        mShutDownTextView.setText(shutgun_timeString);
                        mTotalDuTextView.setText(energyString);
                        mTotalStereTextView.setText(String.format("%.3f ", water_cap / 1000));
                        setTotalTime(motor_runed_time);

                        setTotalPower();
                        setTotalWater();
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                break;
                default:
                    break;
            }
        };
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        switch (resultCode) {
            case CONNECTED_FLAG: {
                boolean runing = data.getBooleanExtra(MOTOR_RUNING, false);
                Message message = new Message();
                message.what = CONNECTED_FLAG;
                Bundle bundle = new Bundle();
                bundle.putBoolean(MOTOR_RUNING, runing);
                message.setData(bundle);
                mHandler.sendMessage(message);
            }
            break;
            case UPDATE_DEV_INFO: {
                Log.i(TAG, " device status");
                Message message = new Message();
                message.what = UPDATE_DEV_INFO;

                Bundle bundle = new Bundle();
                bundle.putString(MOTOR_DEV_INFO, data.getStringExtra(MOTOR_DEV_INFO));
                message.setData(bundle);
                mHandler.sendMessage(message);
            }
            break;
            default:
                break;
        }

    }


    /*显示对话框  设置水价，电费
     * i 0=电费  1=水费
     * digits
     * input_type 设置输入类型
     * message 消息
     * unit
     * priceTextView
     * totalTextView
     * */
    private void showDialog(final int i, String digits, int input_type, String message, String unit, final TextView priceTextView, final TextView totalTextView) {

        mSelfDialog = new SelfDialog(getActivity());	//在当前界面新建一个对话框
        String str;										//定义字符串
        Window mWindow = mSelfDialog.getWindow();		//获取对话框窗口
        WindowManager.LayoutParams lp = mWindow.getAttributes();
        mWindow.setGravity(Gravity.TOP);
        lp.y = 300;// 设置竖直偏移量
        if(0 == i)	str = mPowerPricePerDuTextView.getText().toString().trim(); //获取电费数值
        else str = mWaterPricePerStereTextView.getText().toString().trim();	//获取水费数值
        mSelfDialog.setTitle(message);	//显示标题
        mSelfDialog.setMessage(message);	//设置消息

        mSelfDialog.setEditDigits(digits);
        mSelfDialog.setEditType(input_type);
        mSelfDialog.setEditText(str);	//设置EDIT显示文本
        mSelfDialog.setUinit(unit);
        mSelfDialog.setUnitLayoutVisibility(View.GONE);

		/*设置确定按钮事件*/
        mSelfDialog.setYesOnclickListener("确定", new SelfDialog.onYesOnclickListener() {

            @Override
            public void onYesClick(Object data, boolean flg) {
                // TODO Auto-generated method stub

                SharedPreferences mSharedPreferences = getActivity().getSharedPreferences("init", Activity.MODE_PRIVATE);
                Editor EditText = mSharedPreferences.edit();

                float price = Float.parseFloat(data.toString().trim());
                float total = Float.parseFloat(mTotalDuTextView.getText().toString().trim());
                if (i == 0) {
                    EditText.putFloat("power_price", price);
                } else {
                    EditText.putFloat("water_price", price);
                }

                priceTextView.setText(data.toString());
                float value = price * total;
                totalTextView.setText(String.format("%.3f", value));
                EditText.commit();
                mSelfDialog.dismiss();
            }
        });
        mSelfDialog.setNoOnclickListener("取消", new SelfDialog.onNoOnclickListener() {
            @Override
            public void onNoClick() {
                mSelfDialog.dismiss();
            }
        });

        mSelfDialog.show();
    }

}
